package com.zpself.module.算法练习.二叉树;

import java.util.Stack;

//liKou_530. 二叉搜索树的最小绝对差
//二叉搜索树的中序遍历的结果是升序 / 非降序
public class 二叉搜索树的最小绝对差 {

    public static void main(String[] args) {
        TreeNode root = initRoot();
        二叉搜索树的最小绝对差 liKou_530 = new 二叉搜索树的最小绝对差();
        System.out.println(liKou_530.getMinimumDifference(root));
    }

    public int getMinimumDifference(TreeNode root) {
        int min =Integer.MAX_VALUE;
        int pro = Integer.MAX_VALUE;//记录中序遍历时前一个值
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while( !stack.isEmpty()){
            root = stack.pop();
            if(root.left==null && root.right==null){
                min = Math.min(Math.abs(root.val-pro),min);
                pro = root.val;
                continue;
            }
            if(root.right!=null) stack.push(root.right);
            stack.push(new TreeNode(root.val));
            if(root.left!=null) stack.push(root.left);
        }
        return min;
    }

    /**
     *  初始化树
     * @author  ZengPeng
     * @date  2020/10/9
     **/
    private static TreeNode initRoot() {
        TreeNode root = new TreeNode(1);
        TreeNode root_l = new TreeNode(3);
        TreeNode root_r = new TreeNode(2);

        root.right = root_l;
        root_l.left= root_r;
        return root;
    }
}